<?php

if (!function_exists('get_file_url')) {
    function get_file_url($uri) {
        if (strstr($uri, 'http://') || strstr($uri, 'https://')) {
            return $uri;
        }

        return request()->domain().$uri;
    }
}

if (!function_exists('create_order_sn')) {
    function create_order_sn($table, $field, $prefix = '', $rand_suffix_length = 4, $pool = [])
    {
        $suffix = '';
        for ($i = 0; $i < $rand_suffix_length; $i++) {
            if (empty($pool)) {
                $suffix .= rand(0, 9);
            } else {
                $suffix .= $pool[array_rand($pool)];
            }
        }
        $sn = $prefix . date('YmdHis') . $suffix;
        if (\think\Db::name($table)->where($field, $sn)->find()) {
            return create_order_sn($table, $field, $prefix, $rand_suffix_length, $pool);
        }
        return $sn;
    }
}

if (!function_exists('get_age')) {
    function get_age($idcard){
        if(empty($idcard)) return null;
        #  获得出生年月日的时间戳
        $date = strtotime(substr($idcard,6,8));
        #  获得今日的时间戳
        $today = strtotime('today');
        #  得到两个日期相差的大体年数
        $diff = floor(($today-$date)/86400/365);
        #  strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
        $age = strtotime(substr($idcard,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;
        return $age;
    }
}

if (!function_exists('get_sex')) {
    function get_sex($idcard) {
        if(empty($idcard)) return null;

        $sexint = (int) substr($idcard, 16, 1);

        return $sexint % 2 === 0 ? 0 : 1;

    }
}

if (!function_exists('get_birthday')) {
    function get_birthday($idcard) {
        if(empty($idcard)) return null;

        $bir = substr($idcard, 6, 8);

        $year = (int) substr($bir, 0, 4);

        $month = (int) substr($bir, 4, 2);

        $day = (int) substr($bir, 6, 2);

        return $year . "-" . $month . "-" . $day;
    }
}